import axios from 'axios';

const baseUrl = "http://127.0.0.1:8000/api/blog"; // 根据你的后端路由调整URL

// 获取博客列表（支持关键字查询）
export const fetchBlogs = async (keyword = '') => {
  try {
    console.log('blogAction 请求参数:', keyword); // 调试信息
    const response = await axios.get(`${baseUrl}?keyword=${keyword}`);
    console.log('获取的响应数据:', response.data); // 调试信息
    return response.data.blogs;
  } catch (error) {
    console.error('获取博客列表时出错:', error);
    throw new Error(error.response?.data?.message || '获取博客列表失败');
  }
};

// 获取用户通过JWT中的ID
export const fetchUserProfile = async (token) => {
  try {
    const response = await axios.get(`${baseUrl}/profile`, {
      headers: {
        "Authorization": `Bearer ${token}`,
      }
    });
    console.log('blogAction:', response.data); // 调试信息
    return response.data;
   
  } catch (error) {
    console.error('获取用户数据时出错:', error);
    throw new Error(error.response?.data?.message || '获取用户数据失败');
  }
};

// 获取单个博客
export const fetchBlogById = async (id) => {
  try {
    const response = await axios.get(`${baseUrl}/${id}`);
    return response.data;
  } catch (error) {
    console.error('获取博客时出错:', error);
    throw new Error(error.response?.data?.message || '获取博客失败');
  }
};

// 添加博客
// export const addBlog = async (blogData) => {
//   try {
//     const response = await axios.post(`${baseUrl}/add`, blogData);
//     return response.data.blogId;
//   } catch (error) {
//     console.error('添加博客时出错:', error);
//     throw new Error(error.response?.data?.message || '添加博客失败');
//   }
// };
// 添加博客
export const addBlog = async (token, blogData) => {
  try {
    const response = await axios.post(`${baseUrl}/add`, blogData, {
      headers: {
        "Authorization": `Bearer ${token}`,
        "Content-Type": "application/json",
      },
    });
    return response.data.blogId;
  } catch (error) {
    if (error.response && error.response.status === 401) {
      throw new Error('未携带token或token失效');
    } else {
      throw new Error(error.response?.data?.message || '添加博客失败');
    }
  }
};
// 更新博客
export const updateBlog = async (id, blogData) => {
  try {
    await axios.put(`${baseUrl}/${id}`, blogData);
    return { message: '博客更新成功' };
  } catch (error) {
    console.error('更新博客时出错:', error);
    throw new Error(error.response?.data?.message || '更新博客失败');
  }
};

// 删除博客
export const deleteBlog = async (id) => {
  try {
    await axios.delete(`${baseUrl}/${id}`);
    return { message: '博客删除成功' };
  } catch (error) {
    console.error('删除博客时出错:', error);
    throw new Error(error.response?.data?.message || '删除博客失败');
  }
};

// // 上传文件
// export const uploadFile = async (formData) => {
//   try {
//     const response = await axios.post(`${baseUrl}/upload`, formData, {
//       headers: {
//         'Content-Type': 'multipart/form-data',
//       },
//     });
//     return response.data.file;
//   } catch (error) {
//     console.error('上传文件时出错:', error);
//     throw new Error(error.response?.data?.message || '上传文件失败');
//   }
// };

// // 下载文件
// export const downloadFile = async (filename) => {
//   try {
//     const response = await axios.get(`${baseUrl}/download/${filename}`, {
//       responseType: 'blob',
//     });
//     const url = window.URL.createObjectURL(new Blob([response.data]));
//     const link = document.createElement('a');
//     link.href = url;
//     link.setAttribute('download', filename);
//     document.body.appendChild(link);
//     link.click();
//   } catch (error) {
//     console.error('下载文件时出错:', error);
//     throw new Error(error.response?.data?.message || '下载文件失败');
//   }
// };
